(()=>{
	let version = false;
	let locversion = false;
	
	function _main() {
		if(_isVersionLt(1)) {
			//config table
			_run(`
				CREATE TABLE "config"(
					id INTEGER PRIMARY KEY AUTOINCREMENT,
					key CHAR(255) NOT NULL,
					value TEXT     NOT NULL
				);`);
			_run(`CREATE INDEX config_index_key ON "config"("key");`);
			Log.addLine(`Create table 'config'`);
			
			// category table
			_run(`
				CREATE TABLE "category"(
					id INTEGER PRIMARY KEY AUTOINCREMENT,
					name CHAR(255),
					parent INT,
					icon TEXT,
					position INT,
					idx_empty INT(1)
				);`);
			_run(`CREATE INDEX category ON "category"("name");`);
			Log.addLine(`Create table 'category'`);
			
			//page table
			_run(`
				CREATE TABLE "page"(
					id INTEGER PRIMARY KEY AUTOINCREMENT,
					name CHAR(255),
					position INT,
					category INT
				);`);
			_run(`CREATE INDEX page_index_name ON "page"("name");`);
			Log.addLine(`Create table 'page'`);
			
			//block table
			_run(`
				CREATE TABLE "block"(
					id INTEGER PRIMARY KEY AUTOINCREMENT,
					label CHAR(255),
					page_id INT,
					type CHAR(255),
					value TEXT,
					position INT,
					parent INT,
					other_config TEXT
				);`);
			_run(`CREATE INDEX block_index_name ON "block"("name");`);
			Log.addLine(`Create table 'block'`);
			
			//page search index table
			_run(`
				CREATE TABLE "index_page"(
					id INTEGER PRIMARY KEY AUTOINCREMENT,
					page_id INT,
					index_value TEXT
				);`);
			_run(`CREATE INDEX index_page_index_index_value ON "index_page"("index_value");`);
			Log.addLine(`Create table 'index_page'`);
			
			
			ConfigModel.saveKeyValue('current_version', '1');
			Log.addLine(`Set version to 1`);
		}
		
		if(_isVersionLt('1.0.02')) {
			_run(`ALTER TABLE 'block' ADD 'comment' TEXT;`);
		}
		
		if(_isVersionLt(COREVAR.VERSION)) {
			ConfigModel.saveKeyValue('current_version', COREVAR.VERSION);
			Log.addLine(`Set version to ` + COREVAR.VERSION);
		}
	}
	
	/**
	 * 获取数据库中的版本
	 * @returns {*}
	 * @private
	 */
	function _getVersion() {
		if(version !== false) {
			return version;
		}
		
		return version = ConfigModel.getKeyValue('current_version', '0');
	}
	
	/**
	 * 数据库中的版本是否低于指定版本
	 * @param targetVersion
	 * @returns {boolean}
	 * @private
	 */
	function _isVersionLt(targetVersion) {
		targetVersion = String(targetVersion).split('.').map((row) => {return row.padStart(4, '0')}).join('').padStart(16, '0');
		let dbversion = _getVersion().split('.').map((row) => {return row.padStart(4, '0')}).join('').padStart(16, '0');
		
		return dbversion < targetVersion;
	}
	
	/**
	 * 运行sql
	 * @param sql
	 * @private
	 */
	function _run(sql) {
		return Model.run(sql);
	}
	
	_main();
})();
